package com.ys.service.account.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.util.CheckUtil;
import com.ys.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.account.TcwNeedPayAccount;
import com.ys.entity.account.TcwNeedPayLedgerDetail;
import com.ys.entity.sys.TsUserChange;
import com.ys.enume.account.TcwNeedPayLedgerDetailEnum;
import com.ys.mapper.account.TcwNeedPayLedgerDetailMapper;
import com.ys.service.account.TcwNeedPayLedgerDetailService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;

@Service("tcwNeedPayLedgerDetailService")
public class TcwNeedPayLedgerDetailServiceImpl implements TcwNeedPayLedgerDetailService {

	@Autowired
	private TcwNeedPayLedgerDetailMapper tcwNeedPayLedgerDetailMapper;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	@Autowired
	private CheckUtil checkUtil;
	
	/*
	 * 新增页
	 */
	@Override
	public R add(String needPayAccountCode, String detailArr) throws Exception {
		if (needPayAccountCode == null || needPayAccountCode.length() == 0) {
			return R.error("应付账户编码不能为空");
		} else if (new TcwNeedPayAccount().setCode(needPayAccountCode).count() == 0) {
			return R.error("应付账户不存在");
		}
		
		/*
		 *  验证详情数据物料
		 *  1、编码不能为空
		 *  2、数量不能为空
		 *  3、价格不能为空
		 */
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			BigDecimal costPrice = detailJO.getBigDecimal("costPrice");
			if (costPrice == null) {
				return R.error("成本价不能为空");
			}
			BigDecimal quantity = detailJO.getBigDecimal("quantity");
			if (quantity == null) {
				return R.error("数量不能为空");
			}
			BigDecimal servicePrice = BigDecimal.ZERO;//detailJO.getBigDecimal("servicePrice");
			/*
			if (servicePrice == null) {
				return R.error("服务费不能为空");
			}

			 */
			
			String needPayTypeCode = detailJO.getString("needPayTypeCode");
			if (needPayTypeCode == null || needPayTypeCode.length() == 0) {
				return R.error("应付类型不能为空");
			}
			
			String vjylx = detailJO.getString("vjylx");
			if (vjylx == null || vjylx.length() == 0) {
				return R.error("交易类型不能为空");
			}
			
			String vgsbm = detailJO.getString("vgsbm");
			if (vgsbm == null || vgsbm.length() == 0) {
				return R.error("公司编码不能为空");
			}

			if(checkUtil.isNotNullByObject(detailJO.get("costPrice")) && checkUtil.isNotNullByObject(detailJO.get("proxyPrice"))){
				BigDecimal proxyPrice = detailJO.getBigDecimal("proxyPrice");
				if(proxyPrice.compareTo(BigDecimal.ZERO)!=0 && proxyPrice.compareTo(costPrice)<0){
					return R.error("代理价不能低于成本价");
				}
			}
		}
		
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
		
		// 添加应付台账明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			
			Long createChangeId = tsUserChange.getId();
			String needPayTypeCode = detailJO.getString("needPayTypeCode");
			String vgsbm = detailJO.getString("vgsbm");
			String vjylx = detailJO.getString("vjylx");
			String detailName = detailJO.getString("detailName");
			BigDecimal costPrice = detailJO.getBigDecimal("costPrice");
			BigDecimal quantity = detailJO.getBigDecimal("quantity");
			BigDecimal servicePrice = BigDecimal.ZERO;//detailJO.getBigDecimal("servicePrice");
			String remark = detailJO.getString("remark");
			BigDecimal proxyPrice = BigDecimal.ZERO;
			if(detailJO.getString("proxyPrice")!=null)proxyPrice = detailJO.getBigDecimal("proxyPrice");
			String annexFile = null;
			BigDecimal payedPrice = BigDecimal.ZERO;
			Integer state = TcwNeedPayLedgerDetailEnum.State.NOT_FINISH.value;
			TcwNeedPayLedgerDetail tcwNeedPayLedgerDetail = TcwNeedPayLedgerDetail.tcwNeedPayLedgerDetail(
					needPayAccountCode, createChangeId, needPayTypeCode, vgsbm, vjylx, detailName, costPrice,
					quantity, remark, annexFile, servicePrice, payedPrice, state, proxyPrice,0,1);
			tcwNeedPayLedgerDetailMapper.insert(tcwNeedPayLedgerDetail);
		}
		return R.ok(AddDto.closeAndReload());
	}
	
	/*
	 * 编辑页
	 */
	@Override
	@Transactional
	public R edit(Map<String, Object> params) throws Exception {
		TcwNeedPayLedgerDetail entity = JSON.parseObject(JSON.toJSONString(params), TcwNeedPayLedgerDetail.class);
		/*
		TcwNeedPayLedgerDetail oldInfo = new TcwNeedPayLedgerDetail().setId(entity.getId()).queryFirst();
		if(oldInfo.getTransferStatus()==1){//已划拨:只可修改成本价、备注
			//entity.setProxyPrice(oldInfo.getProxyPrice());
			oldInfo.setCostPrice(entity.getCostPrice());
			oldInfo.setRemark(entity.getRemark());
		}
		if(oldInfo.getState()==1){//已完成:只可修改备注
			//entity.setCostPrice(oldInfo.getCostPrice());
			oldInfo.setRemark(entity.getRemark());
		}

		 */

		if(checkUtil.isNotNullByObject(entity.getCostPrice()) && checkUtil.isNotNullByObject(entity.getProxyPrice())){
			BigDecimal costPrice = entity.getCostPrice();//成本价
			BigDecimal proxyPrice = entity.getProxyPrice();//代理价
			if(proxyPrice.compareTo(BigDecimal.ZERO)!=0 && proxyPrice.compareTo(costPrice)<0){
				R.error("代理价不能低于成本价");
			}
		}
		/*
		//修改
		if(oldInfo.getTransferStatus()==1 || oldInfo.getState()==1){
			tcwNeedPayLedgerDetailMapper.update(oldInfo);
		}else {
			tcwNeedPayLedgerDetailMapper.update(entity);
		}

		 */
		tcwNeedPayLedgerDetailMapper.update(entity);
		return R.ok("操作成功");
	}


	//划拨，生成流水
	@Override
	public R doTransferFlow(Long id) throws Exception{
		TcwNeedPayLedgerDetail entity = new TcwNeedPayLedgerDetail().setId(id).queryFirst();
		if(entity.getTransferStatus() ==1){
			return R.error("已划拨的明细不可再划拨");
		}
		Map<String,Object> info = new TcwNeedPayLedgerDetail()
				.addField("(A.ProxyPrice) * A.Quantity proxyTotalPrice")
				.setId(id)
				.addLeftJoin("TCW_NeedPayAccount P ON P.Code = A.NeedPayAccountCode")//应付账户管理
				.addField("P.Vgsbm AS pVgsbm")//公司编码
				.addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = P.Vgsbm")//运营公司表
				.addField("OCA.Vgsjc AS pVgsjc")//公司简称

				.addLeftJoin("THR_OperateCompanyApply OC ON OC.Vgsbm = A.Vgsbm")//运营公司表
				.addField("OC.Vgsjc AS vgsjc")//公司简称

				.addField("FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS saveTime")//保存时间

				.queryFirstMap();


		if(checkUtil.isNotNullByObject(info.get("vgsbm")) && checkUtil.isNotNullByObject(info.get("pVgsbm"))
				&& checkUtil.isNotNullByObject(info.get("proxyTotalPrice")) && checkUtil.isNotNullByObject(info.get("vjylx"))){
			BigDecimal proxyTotalPrice = new BigDecimal(info.get("proxyTotalPrice").toString());
			/*
			if(proxyTotalPrice.compareTo(BigDecimal.ZERO)>0){
				proxyTotalPrice = proxyTotalPrice.negate();
			}
			 */
			if(proxyTotalPrice.compareTo(BigDecimal.ZERO)!=0){
				Date saveTime = new Date();//DateUtil.parseYYYY_MM_dd_HH_mm_ss(info.get("saveTime").toString());

				String remark = "应付台账";//备注：预支台账+名称+代理价*数量+备注
				if(checkUtil.isNotNullByObject(info.get("detailName"))) remark +="，"+info.get("detailName").toString();
				if(checkUtil.isNotNullByObject(info.get("proxyPrice"))) remark +="，"+info.get("proxyPrice").toString();
				if(checkUtil.isNotNullByObject(info.get("quantity"))) remark +="*"+info.get("quantity").toString();
				if(checkUtil.isNotNullByObject(info.get("remark"))) remark +="，"+info.get("remark").toString();
				//新增流水
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
						info.get("vgsbm").toString(),info.get("vgsjc").toString(),
						info.get("pVgsbm").toString(),info.get("pVgsjc").toString(),
						info.get("vjylx").toString(),proxyTotalPrice.negate(),saveTime, saveTime,
						remark,null,
						saveTime);
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
						info.get("pVgsbm").toString(),info.get("pVgsjc").toString(),
						info.get("vgsbm").toString(),info.get("vgsjc").toString(),
						info.get("vjylx").toString(),proxyTotalPrice,saveTime, saveTime,
						remark,null,
						saveTime);
			}


			//修改划拨状态
			//TcwNeedPayLedgerDetail entity = new TcwNeedPayLedgerDetail();
			entity.setId(id);
			entity.setTransferStatus(1);
			tcwNeedPayLedgerDetailMapper.update(entity);
			return R.ok();
		}else {
			return R.error("运营公司、代理总额等信息不完整！");
		}


	}




	//复制
	@Override
	public R doCopy(Long id) throws Exception{
		TcwNeedPayLedgerDetail entity = new TcwNeedPayLedgerDetail().setId(id).queryFirst();
		if(entity!=null && entity.getStatus()!=null){
			entity.setState(0);
			entity.setTransferStatus(0);
			tcwNeedPayLedgerDetailMapper.insert(entity);
		}
		return R.ok();

	}


	//删除
	@Override
	public R doDel(Long id) throws Exception{
		TcwNeedPayLedgerDetail entity = new TcwNeedPayLedgerDetail().setId(id).queryFirst();
		if(entity!=null && entity.getStatus()!=null){
			if(entity.getState() == 1 ){
				return R.error("已完成的明细不可删除");
			}
			if(entity.getTransferStatus() ==1){
				return R.error("已划拨的明细不可删除");
			}
			tcwNeedPayLedgerDetailMapper.deleteTrue(id);
		}
		return R.ok();

	}



	//设置成本价
	@Override
	public R setUnitPrice(Long id, BigDecimal costPrice) throws Exception{
		TcwNeedPayLedgerDetail entity = new TcwNeedPayLedgerDetail().setId(id).queryFirst();
		if(entity!=null && entity.getStatus()!=null){
			if(entity.getState() == 1 ){
				return R.error("已完成的明细不可修改成本价");
			}
			if(entity.getProxyPrice()!=null){
				BigDecimal proxyPrice = entity.getProxyPrice();//代理价
				if(proxyPrice.compareTo(BigDecimal.ZERO)!=0 && proxyPrice.compareTo(costPrice)<0){
					return R.error("代理价不能低于成本价");
				}
			}
			entity.setCostPrice(costPrice);
			tcwNeedPayLedgerDetailMapper.update(entity);
		}
		return R.ok();

	}



	//设置代理价
	@Override
	public R setProxyPrice(Long id, BigDecimal proxyPrice) throws Exception{
		TcwNeedPayLedgerDetail entity = new TcwNeedPayLedgerDetail().setId(id).queryFirst();
		if(entity!=null && entity.getStatus()!=null){
			if(entity.getTransferStatus() ==1){
				return R.error("已划拨的明细不可修改代理价");
			}
			BigDecimal costPrice = entity.getCostPrice();//成本价
			if(proxyPrice.compareTo(BigDecimal.ZERO)!=0 &&  proxyPrice.compareTo(costPrice)<0){
				return R.error("代理价不能低于成本价");
			}
			entity.setProxyPrice(proxyPrice);
			tcwNeedPayLedgerDetailMapper.update(entity);
		}
		return R.ok();

	}



    //批量修改应付类型
    @Override
    public R setNeedPayType(Long id, String needPayTypeCode) throws Exception{
        TcwNeedPayLedgerDetail entity = new TcwNeedPayLedgerDetail().setId(id).queryFirst();
        if(entity!=null && entity.getTransferStatus()!=null){
            if(entity.getTransferStatus() ==1){
                return R.error("已划拨的明细不可修改应付类型");
            }
            entity.setNeedPayTypeCode(needPayTypeCode);
            tcwNeedPayLedgerDetailMapper.update(entity);
        }
        return R.ok();

    }


	//设置已付金额
	@Override
	public R setPayedPrice(Long id, BigDecimal payedPrice) throws Exception{
		TcwNeedPayLedgerDetail entity = new TcwNeedPayLedgerDetail().setId(id).queryFirst();
		if(entity!=null && entity.getStatus()!=null){
			entity.setPayedPrice(payedPrice);
			tcwNeedPayLedgerDetailMapper.update(entity);
		}
		return R.ok();

	}




	//批量修改交易类型
	@Override
	public R setVjylx(Long id, String vjylx) throws Exception{
		TcwNeedPayLedgerDetail entity = new TcwNeedPayLedgerDetail().setId(id).queryFirst();
		if(entity!=null && entity.getTransferStatus()!=null){
			entity.setVjylx(vjylx);
			tcwNeedPayLedgerDetailMapper.update(entity);
		}
		return R.ok();

	}




}
